<?php

namespace app\merchant_staff\controller\billiard;

use app\common\controller\MerchantStaff;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Area;
use app\common\model\mycurrency\Agent as agent_model;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use app\common\model\mycurrency\MerchantStaff as StaffMoney;

/**
 * 代理or业务员接口
 */
class Agent extends MerchantStaff
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';


    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
//        $params = $this->request->param();
//        $role_type = $params['role_type'];
//        if ($role_type == 1){
//            if (
//                $this->identity == 2 ||
//                $this->agent['level'] == \app\common\model\mycurrency\Agent::LEVEL_QUXIAN ||
//                $this->agent['role_type'] == \app\common\model\mycurrency\Agent::ROLE_TYPE_YEWUYUAN
//            ){//门店 || 区县代理 || 业务员 三个身份无访问权限
//                $this->error('无管理下级代理商权限');
//            }
//        }else{
//            if (
//                $this->identity == 2
//            ){//门店 || 区县代理 || 业务员 三个身份无访问权限
//                $this->error('无管理下级代理商权限');
//            }
//        }

    }

    /**
     * 列表
     */
    public function agentList(){
        $params = $this->request->param();
        $role_type = \app\common\model\mycurrency\Agent::ROLE_TYPE_DAILI.",".\app\common\model\mycurrency\Agent::ROLE_TYPE_YEWUYUAN;
        $rule = [
            ['page', 'require|>:0', '页码不能为空|当前页展示数量必须大于0'],
            ['pageSize', 'require|>:0', '每页查询条数不能为空|每页展示数量必须大于0'],
            ['role_type', "require|in:{$role_type}", '角色角色不能为空|角色类型错误'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'pid' => $this->agent_id,
            'deletetime' => null,
            'role_type' => $params['role_type'],
        ];
        $list = \app\common\model\mycurrency\Agent::where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        $num = \app\common\model\mycurrency\Agent::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 详情
     */
    public function agentInfo(){
        $params = $this->request->param();
        $rule = [
            ['agent_id', 'require', '下级id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $data = \app\common\model\mycurrency\Agent::where(['id' => $params['agent_id'],'pid' => $this->agent_id,'deletetime' => null])->find();
        if(!$data){
            $this->error('代理商不存在');
        }
        $this->success('加载成功',$data);
    }

    /**
     * 添加 - 下级可选地区
     */
    public function agentAddArea(){
        $agency_region_id = \app\common\model\mycurrency\Agent::where(['id' => $this->agent_id])->value('agency_region_id');
        $data = Area::with(['subordinate' =>function($query){
            $query->field('id,shortname,pid');
            $query->with(['subordinate' => function($query){
                $query->field('id,shortname,pid');
            }]);
        }])->where(['pid' => $agency_region_id])->field('id,shortname')->select();
        $this->success('加载成功',$data);
    }

    /**
     * 添加
     */
    public function agentAdd(){
        $params = $this->request->param();
        $rule = [
            ['name', 'require', '身份名称不能为空'],
            ['fullname', 'require', '联系人姓名不能为空'],
            ['phone', ['require','/^1[3-9]\d{9}$/'], ['联系人电话不能为空','联系人手机号格式不正确']],
            ['role_type',"require|in:1,2", '角色不能为空|角色类型错误'],
            ['divideinto',"require", '分成比例不能为空'],
            ['status',"require", '状态不能为空'],

            ['username',"require", '管理员登录账号不能为空'],
            ['password',"require", '管理员登录密码不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($params['role_type'] == agent_model::ROLE_TYPE_DAILI){//如果是区域代理
            //if(!$params['level']){
            //    $this->error('代理等级不能为空');
            //}
            if(!$params['agency_region_id']){
                $this->error('代理地区不能为空');
            }
            $area = \app\admin\model\Area::where(['id' => $params['agency_region_id']])->find();
            $params['level'] = $area->level;
            $mergename = $area->mergename;
            $mergenameArr = explode(',',$mergename);
            unset($mergenameArr[0]);
            foreach ($mergenameArr as $k => $v){
                if ($k == 1){
                    $params['province_id'] = \app\admin\model\Area::where(['name' => $v])->value('id');
                }elseif ($k == 2){
                    $params['city_id'] = \app\admin\model\Area::where(['name' => $v])->value('id');
                }elseif ($k == 3){
                    $params['area_id'] = \app\admin\model\Area::where(['name' => $v])->value('id');
                }
            };
            $params['city'] = $mergename;
        }
        $admin = [
            'username' => $params['username'],
            'password' => $params['password'],
        ];
        unset($params['username']);
        unset($params['password']);
        Db::startTrans();
        try {
            agent_model::agentAdd($params,$admin,$this->agent_id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('添加成功');
    }

    /**
     * 编辑
     */
    public function agentUpdate(){
        $params = $this->request->param();
        $rule = [
            ['name', 'require', '身份名称不能为空'],
            ['fullname', 'require', '联系人姓名不能为空'],
            ['phone', 'require', '联系人电话不能为空'],
            ['divideinto',"require", '分成比例不能为空'],
            ['status',"require", '状态不能为空'],

            ['x_agent_id',"require", '下级id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $x_agent_id = $params['x_agent_id'];
        unset($params['x_agent_id']);

        $x_agent = \app\common\model\mycurrency\Agent::where(['id' => $x_agent_id,'pid' => $this->agent_id,'deletetime' => null])->find();
        if (!$x_agent){
            $this->error('下级代理不存在');
        }
        Db::startTrans();
        try {
            agent_model::agentUpdate($params,$x_agent_id);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('编辑成功');
    }

    /**
     * 删除
     */
    public function agentDel(){
        $params = $this->request->param();
        $rule = [
            ['x_agent_id',"require", '下级id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $x_agent_id = $params['x_agent_id'];
        $x_agent = \app\common\model\mycurrency\Agent::where(['id' => $x_agent_id,'pid' => $this->agent_id,'deletetime' => null])->find();
        if (!$x_agent){
            $this->error('下级代理不存在');
        }
        $x_agent->deletetime = time();
        $x_agent->save();
        $this->success('删除成功');
    }




}
